package org.tao.lightningmq.broker.config;

import io.netty.util.internal.StringUtil;
import org.tao.lightningmq.broker.cache.CommonCache;
import org.tao.lightningmq.common.constants.BrokerConstants;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Properties;

/**
 * @Author lht
 * @date 2025/1/3 - 16:10
 * @description: 全局配置加载器
 */
public class GlobalPropertiesLoader {

    public void loadProperties() {
        GlobalProperties globalProperties = new GlobalProperties();
        String mqHome = System.getenv(BrokerConstants.MQ_HOME);
        if (StringUtil.isNullOrEmpty(mqHome)) {
            throw new IllegalArgumentException("Please set the environment variable " + BrokerConstants.MQ_HOME);
        }
        mqHome = mqHome.replace("\\", "/");
        globalProperties.setMqHome(mqHome);
        Properties properties = new Properties();
        try {
            properties.load(Files.newInputStream(new File(mqHome + BrokerConstants.BROKER_PROPERTIES_PATH).toPath()));
            globalProperties.setNameserverIp(properties.getProperty("nameserver.ip"));
            globalProperties.setNameserverPort(properties.getProperty("nameserver.port"));
            globalProperties.setNameserverUser(properties.getProperty("nameserver.user"));
            globalProperties.setBrokerPort(Integer.valueOf(properties.getProperty("broker.port")));
            globalProperties.setBrokerIp(properties.getProperty("broker.ip"));
            globalProperties.setNameserverPassword(properties.getProperty("nameserver.password"));
            globalProperties.setReBalanceStrategy(properties.getProperty("rebalance.strategy"));
            globalProperties.setBrokerClusterGroup(properties.getProperty("broker.cluster.group"));
            globalProperties.setBrokerClusterMode(properties.getProperty("broker.cluster.mode"));
            globalProperties.setBrokerClusterRole(properties.getProperty("broker.cluster.role"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        CommonCache.setGlobalProperties(globalProperties);
    }

}
